import pandas as pd
import matplotlib.pylab as plt
import lightgbm as lgb
from sklearn.model_selection import train_test_split

# read data
data = pd.read_csv('data_fs.csv')
drop_col = ['Index','Src IP','Dst IP','Src Port','Dst Port','Flow Duration','Packet Number','Fwd Packet Number','Bwd Packet Number','Total Bytes','Total Fwd Bytes','Total Bwd Bytes','Label']
feature_names = list(data.drop(drop_col, axis=1).columns)

# 数据集划分特征矩阵X和目标变量y
X = data.drop(drop_col, axis=1)
y = data['Label']

X_train,X_test,y_train,y_test =train_test_split(X,y,test_size=0.2)

#print(X_train)
#print(X_test)

# 创建成lgb特征的数据集格式
lgb_train = lgb.Dataset(X, y) # 将数据保存到LightGBM二进制文件将使加载更快
#lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)  # 创建验证数据


# 将参数写成字典下形式
params = {
    'task': 'train',
    'boosting_type': 'gbdt',  # 设置提升类型
    'objective': 'regression', # 目标函数
    'metric': {'l2', 'auc'},  # 评估函数
    'num_leaves': 31,   # 叶子节点数
    'num_trees': 50,
    'learning_rate': 0.05,  # 学习速率
    'feature_fraction': 0.9, # 建树的特征选择比例
    'bagging_fraction': 0.8, # 建树的样本采样比例
    'bagging_freq': 5,  # k 意味着每 k 次迭代执行bagging
    'verbose': 1 # <0 显示致命的, =0 显示错误 (警告), >0 显示信息
}
 
print('Start training...')
# 训练 cv and train
model = lgb.train(params,lgb_train,num_boost_round=20,valid_sets=lgb_train) # 训练数据需要参数列表和数据集


plt.rcParams['figure.autolayout'] = True
lgb.plot_importance(model, max_num_features=20, title='feature importance', xlabel='score', ylabel='feature', grid=False)

plt.show()
